import pika

HOST = '127.0.0.1'
PORT = 5672


def callback(ch, method, properties, body):
    # 回调函数,处理从rabbitmq中取出的消息
    print(ch)
    print(method)
    print(properties)
    print(body.decode('utf-8'))
    print(" [x] Received %r" % body)


class RabbitMQHelper(object):

    def __init__(self, host=HOST, port=PORT, channel_name="channel01"):
        # 定义连接池
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=host, port=port))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=channel_name)
        self.channel_name = channel_name

    def publish(self, msg):
        # 注意当未定义exchange时，routing_key需和queue的值保持一致
        return self.channel.basic_publish(exchange='', routing_key=self.channel_name, body=msg)

    def subscribe(self):
        self.channel.basic_consume(self.channel_name, callback, auto_ack=True)
        print(' [*] Waiting for messages. To exit press CTRL+C')
        # 开始监听 接受消息
        self.channel.start_consuming()

    def disconnect(self):
        self.connection.close()
